package com.hsmw.common.base;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.htn.common.core.utils.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public abstract class BaseService<M extends BaseMapper<T>, T extends BaseModel> extends ServiceImpl<M, T> {

    private String modelSuffix = null;

    @Override
    public boolean save(T entity) {
        if(StringUtils.isBlank(entity.getId())){
            entity.setId(generateId(entity));
        }
        if(StringUtils.isNotNull(entity.getCreateTime())){
            entity.setCreateTime(LocalDateTime.now());
        }
//        entity.setCreateUser(BaseContextHandler.getUserId());
        return super.save(entity);
    }

    @Override
    public boolean saveBatch(Collection<T> entityList) {
        entityList.forEach(entity->{
            if(StringUtils.isBlank(entity.getId())){
                entity.setId(generateId(entity));
            }
            entity.setCreateTime(LocalDateTime.now());
//            entity.setCreateUser(BaseContextHandler.getUserId());
        });
        return super.saveBatch(entityList);
    }

    @Override
    public boolean updateById(T entity) {
        entity.setUpdateTime(LocalDateTime.now());
//        entity.setUpdateUser(BaseContextHandler.getUserId());
        return super.updateById(entity);
    }

    public String generateId(T entity){
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyyMMddHH");
        String ID = "HTN"+dtf2.format(LocalDateTime.now())+""+getStringRandom(6)+generateRandomNum();
        //ID = ID+num+generateOrderdentifyNum();
        return ID;
        //return String.format("%1$s%2$ts%3$s", obtainAbbreviation(entity), System.currentTimeMillis(), createUID());
    }

    private String obtainAbbreviation(T entity){
        if(modelSuffix == null){
            String sn = entity.getClass().getSimpleName();
            modelSuffix = sn.split("\\$\\$EnhancerByCGLIB\\$\\$")[0].replaceAll("[^A-Z]", "");
        }

        return modelSuffix;
    }

    private String createUID() {
        String uuid = UUID.randomUUID().toString();
        return uuid.substring(uuid.lastIndexOf("-") + 1, uuid.length());
    }
    public static String getStringRandom(int length) {

        String val = "";
        Random random = new Random();
        //参数length，表示生成几位随机数
        for(int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if("char".equalsIgnoreCase(charOrNum)){
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char)(random.nextInt(26) + temp);
            }else if("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

    public static String generateRandomNum() {
        String code = "";
        try {
            Random random = new Random();
            for (int i = 0; i < 4; i++) {
                code += random.nextInt(10);
            }
            return code;
        }catch (Exception e){
            e.printStackTrace();
            return "0";
        }
    }
}
